<template>
  <el-row class="login-container">
      <el-col :lg="16" :md="12" class="left">
          <div>
              <div>欢迎光临</div>
              <div>此站点是《vue3 + vite实战商城后台开发》视频课程的演示地址</div>
          </div>
      </el-col>
      <el-col :lg="8" :md="12" class="right">
          <h2 class="title">欢迎回来</h2>
          <div>
              <span class="line"></span>
              <span>账号密码登录</span>
              <span class="line"></span>
          </div>
          <el-form ref="formRef" :rules="rules" :model="form" class="w-[250px]">
              <!-- <el-form-item prop="username">
                  <el-input v-model="form.username" placeholder="请输入邮箱">
                      <template #prefix>
                          <el-icon><user /></el-icon>
                      </template>
                  </el-input>
              </el-form-item> -->
              <el-form-item prop="to">
                  <el-input v-model="form.to" placeholder="请输入手机号">
                      <template #prefix>
                          <el-icon><user /></el-icon>
                      </template>
                  </el-input>
              </el-form-item>
            <el-form-item>
              <el-image
                   :src="imageUrl"
                    style="width: 100px; height: 40px;float:right;cursor: pointer;"
                     @click="uploadImage" ></el-image>
            </el-form-item>
              <el-form-item prop="captcha">
                  <el-input type="captcha" v-model="form.captcha" placeholder="请输入验证码" show-password>
                      <template #prefix>
                          <el-icon><lock /></el-icon>
                      </template>
                  </el-input>
                  <el-col :span="6">
                    <el-button @click="sendCode" :disabled="isCountingDown">{{btnText}}</el-button>
                </el-col>
              </el-form-item>
              <el-form-item prop="code">
                  <el-input type="code" v-model="form.code" placeholder="请输入手机验证码" show-password>
                      <template #prefix>
                          <el-icon><lock /></el-icon>
                      </template>
                  </el-input>
              </el-form-item>
              <el-form-item>
                <el-col :span="6">
                    <el-button v-if="showCountdown">重新发送验证码: {{ countdown }} 秒后</el-button>
                </el-col>
              </el-form-item>
              <el-form-item>
                  <el-button round color="#626aef" class="w-[250px]" type="primary" @click="onSubmit">登录</el-button>
              </el-form-item>
          </el-form>
      </el-col>
  </el-row>
</template>

<script setup>
import { ref,reactive, onMounted,computed  } from 'vue'
import { ElNotification } from 'element-plus'
import { useRouter } from 'vue-router'
import requestUtil,{getServerUrl} from "@/util/request"
import store from '@/stores'

const countdown = ref(0);
const isCountingDown = computed(() => countdown.value > 0);
const showCountdown = ref(false);

const startCountdown = () => {
      countdown.value = 60; // 倒计时60秒
      showCountdown.value = true;
      const interval = setInterval(() => {
        countdown.value--;
        if (countdown.value <= 0) {
          clearInterval(interval);
          showCountdown.value = false;
        }
      }, 1000);
    };
    const btnText = computed(() => {
      return isCountingDown.value ? '等待重试' : '提交';
    });
// do not use same name with ref
const form = reactive({
   to:"",
   captcha:"",
   codeType: "1"
})
const imageUrl = ref("")

const router = useRouter()
const rules = {
  to:[
      { 
          required: true, 
          message: '手机号不能为空', 
          trigger: 'blur' 
      },
  ],
  captcha:[
      { 
          required: true, 
          message: '验证码不能为空', 
          trigger: 'blur' 
      },
  ]
}

const formRef = ref(null)

const sendCode = () =>{
  formRef.value.validate((valid)=>{
      if(!valid){
          return false
      }
      const res= requestUtil.get("member/sys/user/send_code",form).then((res) => {
       if(res.data.code == 200){
          ElNotification({
            message: "发送验证码成功",
            type: 'success',
            duration:3000
          })
       }else{
        startCountdown()
      }
  })
      .catch(err=>{
           
        ElNotification({
            message: "发送验证码失败",
            type: 'fail',
            duration:3000
          })
      })
  })
}

const onSubmit = () => {
  formRef.value.validate((valid)=>{
      if(!valid){
          return false
      }
      
      const res= requestUtil.post("member/sys/user/test/login",form).then((res) => {
        console.log(res.data.code)
        if(res.data.code == 200){
          const token = res.data.msg
          store.commit('SET_TOKEN',token);
          ElNotification({
            message: "登录成功！！",
            type: 'success',
            duration:3000
          })
          router.push("/")
       
        }else{
          ElNotification({
            message: res.data.msg,
            type: 'fail',
            duration:3000
          })
        }
      }).catch(err=>{
           
           ElNotification({
               message: res.data,
               type: 'fail',
               duration:3000 
             })
         })
    })
}

    // 获取验证码图片
    const uploadImage = ()=>{ 
        imageUrl.value = "http://localhost:8000/member/sys/user/kaptcha?d="+new Date()
    }



//组件挂载
 onMounted(() => {
      // 在这里可以执行DOM操作或数据请求
      console.log('组件已挂载');
      uploadImage()
 });

</script>

<style scoped>
.login-container{
  @apply min-h-screen bg-indigo-500;
}
.login-container .left,.login-container .right{
  @apply flex items-center justify-center;
}
.login-container .right{
  @apply bg-light-50 flex-col;
}
.left>div>div:first-child{
  @apply font-bold text-5xl text-light-50 mb-4;
}
.left>div>div:last-child{
  @apply text-gray-200 text-sm;
}
.right .title{
  @apply font-bold text-3xl text-gray-800;
}
.right>div{
  @apply flex items-center justify-center my-5 text-gray-300 space-x-2;
}
.right .line{
  @apply h-[1px] w-16 bg-gray-200;
}
</style>